#include <QPainter>
#include <QFontMetrics>
#include <QTextDocument>

#include <Plasma/Plasma>
#include <Plasma/Applet>
#include <Plasma/DataEngine>

#include "cfg.h"
#include "coverok.h"

K_EXPORT_PLASMA_APPLET(coverok, Coverok)

#define DATA_POLLING_INTERVAL 1000

static const char amarok_source_name[] = "org.mpris.amarok";
static const char data_engine_name[] = "nowplaying";

Coverok::Coverok(QObject *parent, const QVariantList &args) : Plasma::Applet(parent, args),
	m_Visible(false)
{
	setBackgroundHints(NoBackground);

	if (immutability() != Plasma::Mutable) hide();

	// in API from 4.4
	connect(this, SIGNAL(immutabilityChanged(Plasma::ImmutabilityType)),
			SLOT(setImmutabilityChanged(Plasma::ImmutabilityType)));
}

Coverok::~Coverok()
{
	if (hasFailedToLaunch()) {
		// Do some cleanup here
	} else {
		// Save settings
	}
}

void Coverok::loadCfg()
{
	m_Cfg.load("/home/bmk/src/coverok/skin/");
	m_Cover = m_Cfg.m_cover.no_cover_pix;
	m_Text.setTextWidth(m_Cfg.m_text.rect.width());

	resize(m_Cfg.m_width, m_Cfg.m_height);
}

void Coverok::init()
{
	Plasma::DataEngine *m_PlayerEngine = dataEngine(data_engine_name);
	if (m_PlayerEngine) {
		connect(m_PlayerEngine, SIGNAL(sourceAdded(QString)),
				SLOT(playerAdded(QString)));
		connect(m_PlayerEngine, SIGNAL(sourceRemoved(QString)),
				SLOT(playerRemoved(QString)));

		loadCfg();

		if (m_PlayerEngine->sources().contains(amarok_source_name))
			showInterface(true);
	} else setFailedToLaunch(true, tr("Cannot load \"nowplaying\" data engine."));
} 

void Coverok::setImmutabilityChanged(const Plasma::ImmutabilityType immutable)
{
	if (immutable == Plasma::Mutable) show();
	else if (!m_Visible) hide();
}

void Coverok::showInterface(bool visible)
{
	if (visible == m_Visible) return;

	if (visible) {
		dataEngine(data_engine_name)->connectSource(amarok_source_name, this,
													DATA_POLLING_INTERVAL);
		show();
	} else {
		hide();
	}

	m_Visible = visible;
}

void Coverok::playerAdded(const QString &name)
{
	if (name == amarok_source_name) showInterface(true);
}

void Coverok::playerRemoved(const QString &name)
{
	if ((name == amarok_source_name) && (immutability() != Plasma::Mutable))
		showInterface(false);
}

void Coverok::paintInterface(QPainter *p, const QStyleOptionGraphicsItem */*option*/,
							 const QRect &contentsRect)
{
	p->setRenderHint(QPainter::SmoothPixmapTransform);
	p->setRenderHint(QPainter::Antialiasing);

	p->save();
	p->translate(m_Cfg.m_merged.rotation.pt.x(), m_Cfg.m_merged.rotation.pt.y());
	if (m_Cfg.m_merged.rotation.angle) p->rotate(m_Cfg.m_merged.rotation.angle);
	p->translate(-m_Cfg.m_merged.rotation.pt.x(), -m_Cfg.m_merged.rotation.pt.y());
	p->translate(m_Cfg.m_merged.rect.x(), m_Cfg.m_merged.rect.y());
	p->drawPixmap(m_Cfg.m_cover.rect.x(), m_Cfg.m_cover.rect.y(), m_Cover);
	if (!m_Cfg.m_top.pix.isNull())
		p->drawPixmap(m_Cfg.m_top.pt.x(), m_Cfg.m_top.pt.y(), m_Cfg.m_top.pix);
	p->restore();

	p->translate(m_Cfg.m_text.rect.x(), m_Cfg.m_text.rect.y());
	m_Text.drawContents(p, QRectF(0, 0, m_Cfg.m_text.rect.width(),
								  m_Cfg.m_text.rect.height()));
}

void Coverok::dataUpdated(const QString &/*sourceName*/, const Plasma::DataEngine::Data &data)
{
	QString title = data["Title"].toString();
	QString artist = data["Artist"].toString();
	QString album = data["Album"].toString();

	if ((title != m_Title) || (artist != m_Artist) || (album != m_Album)) {
		m_Title = title;
		m_Artist = artist;
		m_Album = album;
// 		printf("title: %s\n", m_Title.toAscii().constData());

		m_Cover = data["Artwork"].value<QPixmap>();
		if (m_Cover.isNull()) m_Cover = m_Cfg.m_cover.no_cover_pix;
		else m_Cover = m_Cover.scaled(m_Cfg.m_cover.rect.width(),
			m_Cfg.m_cover.rect.height());
	}

	QString s = "<div style=\"color:white\">";
	if (!m_Title.isEmpty()) s += "<big><b>" + m_Title + "</b></big><br>";
	if (!m_Artist.isEmpty()) s += tr("przez") + " <big><b>" + m_Artist + "</b></big><br>";
	if (!m_Album.isEmpty()) s += tr("na") + " <big><b>" + m_Album + "</b></big>";
	s += "</div>";
	m_Text.setHtml(s);

	update();
}

#include "coverok.moc"
